package com.qq.Servlet.Book;

import com.qq.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

//center过滤器的注解
@WebServlet("/center/book/add")
public class BookAddServlet extends HttpServlet {
//doGet显示添加用的表单就是当我们点击添加时就会用到doGet
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/jsp/book/addForm.jsp").forward(req,resp);
    }
//执行将我们要添加的书籍插入到数据库
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String name  = req.getParameter("name");
        String author  = req.getParameter("author");
        String price  = req.getParameter("price");
        Connection con = DBUtil.getConnection();
       try {
           //对插入书籍进行操作
           PreparedStatement ps = con.prepareStatement("insert into book(name ,author,price) values (?,?,?)");
//           这里是对三个问号进行一一对应
           ps.setString(1,name);
           ps.setString(2,author);
           ps.setDouble(3,Double.parseDouble(price));
           int num = ps.executeUpdate();
           System.out.println("====>"+num);
               //使用重定项，添加成功回到BookServlet再回到index.jsp页面
           resp.sendRedirect("index01");

       }catch (SQLException e){
           e.printStackTrace();
       }
    }
}
